package com.welkom.everydate.dao;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapExecutor;

import java.sql.SQLException;
import java.util.List;
import javax.annotation.Resource;
import javax.annotation.PostConstruct;
/**
 * Created with IntelliJ IDEA.
 * User: v.wupingteng
 * Date: 12-8-15
 * To change this template use File | Settings | File Templates.
 */
public abstract class BaseDao extends SqlMapClientDaoSupport {
    /**
     * Logger available to subclasses
     */
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    
    
    
    @Resource(name = "sqlMapClient")
    private SqlMapClient sqlMapClient;
    @PostConstruct
        public void initSqlMapClient(){
         super.setSqlMapClient(sqlMapClient);
    }
   
    /**
     * @param id
     * @param paramObject
     * @return
     * @throws Exception
     */
    protected Object getObject(String id, final Object paramObject) throws Exception {

        Object result = null;
        try {
            result = getSqlMapClientTemplate().queryForObject(id, paramObject);
        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
            throw e;
        }

        return result;
    }

    protected List<?> getObjects(String id, final Object paramObject) {

        List<?> result = null;
        try {
            result = getSqlMapClientTemplate().queryForList(id, paramObject);
        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
        }

        return result;
    }

    protected void insertBath(final String id, final List<?> beans) {
        getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
            public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
                executor.startBatch();
                for (Object bean : beans) {
                    executor.insert(id, bean);
                }
                executor.executeBatch();
                return null;
            }
        });
    }

    protected void update(String id, final Object paramObject) throws Exception {
        getSqlMapClientTemplate().update(id, paramObject);
    }

    protected void insert(String id, final Object paramObject) throws Exception {
        List<?> result = null;
        try {
            getSqlMapClientTemplate().insert(id, paramObject);
        } catch (Exception e) {
            logger.error(e.getStackTrace().toString());
            throw e;
        }
    }

}
